package archforce.atp.x.ui.impl.common.component;

import archforce.atp.x.ui.frame.component.AbstractRowItemComponent;
import archforce.atp.x.ui.impl.left.IPPortModel;

import javax.swing.*;
import java.awt.*;
import java.util.Objects;

/**
 * @author wx
 * @version 1.0
 * @date 2022/4/8 10:08
 */
public class IPPortItemComponent extends AbstractRowItemComponent<IPPortModel> {
    private JIpAddressField ipInput;
    private JTextField portInput;

    private static final Integer DEFAULT_PORT = 22;

    public IPPortItemComponent() {
        this(true);
    }

    public IPPortItemComponent(boolean blank) {
        super();
        IPPortModel data = new IPPortModel(blank);
        init(data);
    }

    public IPPortItemComponent(IPPortModel data) {
        super();
        init(data);
    }

    private void init(IPPortModel data){
        this.ipInput = new JIpAddressField();
        this.ipInput.setText(data.getIp());
        this.portInput = initTextField();
        this.portInput.setText(Objects.isNull(data.getPort())?DEFAULT_PORT.toString():String.valueOf(data.getPort()));
        FlowLayout flowLayout = new FlowLayout();
        flowLayout.setAlignment(FlowLayout.LEFT);
        setLayout(flowLayout);
        add(this.ipInput);
        add(this.portInput);
    }


    private JTextField initTextField(){
        JTextField textField = new JTextField();
        textField.setColumns(4);
        return textField;
    }

    public JIpAddressField getIpInput() {
        return ipInput;
    }

    public void setIpInput(JIpAddressField ipInput) {
        this.ipInput = ipInput;
    }

    public JTextField getPortInput() {
        return portInput;
    }

    public void setPortInput(JTextField portInput) {
        this.portInput = portInput;
    }

    @Override
    public void setBindData(IPPortModel bindData) {
        this.ipInput.setIpAddress(bindData.getIp());
        Integer port = bindData.getPort();
        this.portInput.setText(port == null?String.valueOf(DEFAULT_PORT):port.toString());
    }

    @Override
    public IPPortModel getBindData() {
        String ipAddress = this.ipInput.getIpAddress();
        String port = this.portInput.getText();
        return new IPPortModel(ipAddress, Integer.valueOf(port==null||"".equals(port)? String.valueOf(DEFAULT_PORT):port));
    }
}
